package com.jxau.mall.user.controller;

import com.jxau.mall.common.util.JwtUtils;
import com.jxau.mall.common.util.ResponseVO;
import com.jxau.mall.user.entity.UserInfo;
import com.jxau.mall.user.model.UserLogin;
import com.jxau.mall.user.service.ILoginService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: shop
 * @description: 登录控制器类
 * @author: guojiani
 * @create: 2025-04-24 20:03
 **/
@RestController // 控制器
@RequestMapping("/login")
public class UserLoginController {
    @Autowired // 注入业务层
    private ILoginService loginService;
    @PostMapping
    public ResponseVO<UserInfo> login(@RequestBody UserLogin userLogin, HttpServletResponse response) throws Exception {
        // 登录
        UserInfo userInfo = loginService.login(userLogin.getUsername(), userLogin.getPassword());
        // 登录成功后创建token，并保存用户信息
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userInfo.getId());
        String token = JwtUtils.generateToken(map);
        // 将token写入响应头
        response.setHeader("Authorization", token);
        return ResponseVO.success(userInfo);
    }
}
